package com.study.talk.ui.adapter.chat

import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import androidx.appcompat.widget.LinearLayoutCompat
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.study.common.ToastUtil
import com.study.talk.R
import com.study.talk.ui.adapter.base.BaseListAdapter
import com.study.talk.databinding.ChatMsgItemBinding
import com.study.talk.data.model.MessageRecord
import com.study.talk.ui.app.chat.ChatViewModel
import com.study.talk.ui.app.self.SelfActivity
import com.study.talk.utils.TimeAgoUtils
import com.study.talk.utils.extras.start
import com.study.talk.utils.extras.toImage
import com.study.talk.utils.extras.toUserDetails

class ChatMsgAdapter(private val chatViewModel: ChatViewModel) :
    BaseListAdapter<MessageRecord, ChatMsgAdapter.ViewHolder>() {

    class ViewHolder(val context: Context, val binding: ChatMsgItemBinding) :
        RecyclerView.ViewHolder(binding.root)

    private val selectMap = mutableMapOf<Int, Boolean>()


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
            parent.context, DataBindingUtil.inflate(
                LayoutInflater.from(parent.context), R.layout.chat_msg_item, parent, false
            )
        )
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int, payloads: MutableList<Any>) {
        if (payloads.isEmpty()) {
            super.onBindViewHolder(holder, position, payloads)
        } else {
            for (payload in payloads) {
                when (payload as String) {
                    "select" -> selectMode(holder, position, true)
                    "normal" -> selectMode(holder, position, false)
                }
            }
        }
    }

    private fun selectMode(holder: ViewHolder, position: Int, mode: Boolean) {
        holder.binding.chatMsgSelect.isChecked = selectMap.getOrDefault(getItem(position).id, false)
        holder.binding.chatMsgSelect.visibility = if (mode) View.VISIBLE else View.GONE
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val msg = getItem(position)
        holder.binding.msg = msg
        //选中 or 取消选中消息
        holder.binding.chatMsgSelect.setOnCheckedChangeListener { _, isChecked ->
            selectMap[msg.id] = isChecked
        }
        if (msg.self) { //自己发出的消息
            holder.binding.chatMsgRight.chatMsgRightLayout.visibility = View.VISIBLE
            holder.binding.chatMsgRight.msgContentTime.text = TimeAgoUtils.format(msg.dateTime)
            holder.binding.chatMsgRight.msgContentHeadImg.setOnClickListener {
                holder.context.apply {
                    start(SelfActivity::class.java)
                }
            }
            holder.binding.chatMsgRight.msgContentImageView.setOnClickListener {
                imageOnClickListener(getItem(position).content, holder.context)
            }
            holder.binding.chatMsgRight.msgContentTextView.setOnLongClickListener { view ->
                showMenu(position, view)
                return@setOnLongClickListener true
            }
        } else {  //对方发出的消息
            holder.binding.chatMsgLeft.chatMsgLeftLayout.visibility = View.VISIBLE
            holder.binding.chatMsgLeft.msgContentTime.text = TimeAgoUtils.format(msg.dateTime)
            holder.binding.chatMsgLeft.msgContentHeadImg.setOnClickListener {
                holder.context.apply {
                   toUserDetails(msg.userId)
                }
            }
            holder.binding.chatMsgLeft.msgContentImageView.setOnClickListener {
                imageOnClickListener(getItem(position).content, holder.context)
            }
            holder.binding.chatMsgLeft.msgContentTextView.setOnLongClickListener { view ->
                showMenu(position, view)
                return@setOnLongClickListener true
            }
        }
    }

    override fun getItemViewType(position: Int): Int {
        return position
    }


    /** 设置消息列表中图片的点击事件 */
    private fun imageOnClickListener(content: String, context: Context) {
        val images = mutableListOf<String>()
        currentList.filter { it.messageType == 1 }.mapTo(images) { it.content }
        val position = images.indexOf(content)
        context.apply {
            toImage(images,position)
        }
    }

    /** 长按消息体弹窗 */
    private fun showMenu(position: Int, view: View) {
        val contentView = createContentView(view)
        val window = createPopupView(contentView, view)
        val entry = IntArray(2)
        view.getLocationOnScreen(entry)
        window.showAtLocation(
            view,
            Gravity.NO_GRAVITY,
            entry[0] + view.width / 2 - contentView.width / 2,
            entry[1] - contentView.height - 20
        )
        initPopupWindowAction(contentView, window, position)
    }

    /** 初始化popupWindow的ContentView */
    private fun createContentView(view: View): View {
        return LayoutInflater.from(view.context).inflate(R.layout.msg_pop_option, null).apply {
            measure(
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
            )
            layout(0, 0, measuredWidth, measuredHeight)
        }
    }

    /** 创建PopupWindow */
    private fun createPopupView(contentView: View, contextView: View): PopupWindow {
        val window = PopupWindow(
            contextView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT
        )
        window.isOutsideTouchable = true
        window.isFocusable = true
        window.isTouchable = true
        window.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        window.contentView = contentView
        return window
    }

    /** 初始化popupWindow中ContentView内部子View的点击事件 */
    private fun initPopupWindowAction(
        popView: View, popupWindow: PopupWindow, position: Int
    ) {
        popView.findViewById<LinearLayoutCompat>(R.id.msg_option_multiply_select)
            .setOnClickListener {
                selectMap[getItem(position).id] = true
                chatViewModel.changeSelectModel(true)
                popupWindow.dismiss()
            }

        popView.findViewById<LinearLayoutCompat>(R.id.msg_option_smart_analyze).setOnClickListener {
            chatViewModel.notifyAnalyzeContent(getItem(position).content)
            popupWindow.dismiss()
        }

        popView.findViewById<LinearLayoutCompat>(R.id.msg_option_other).setOnClickListener {
            ToastUtil.showToast(it.context, "功能开发中")
            popupWindow.dismiss()
        }
    }

    fun selectModel() {
        for (i in 0 until itemCount) {
            notifyItemChanged(i, "select")
        }
    }

    /** 普通模式 */
    fun normalModel() {
        for (i in 0 until itemCount) {
            notifyItemChanged(i, "normal")
        }
        clearSelected()
    }

    /** 多选模式 */
    fun getSelectMsg(): List<MessageRecord> {
        return currentList.filter {
            selectMap.getOrDefault(it.id, false)
        }
    }

    /** 清除所有的选择 */
    fun clearSelected() {
        selectMap.clear()
    }
}